<template>
  <!-- 分配权限的弹层 -->
  <el-dialog
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    :visible="showAssignDialog"
    @close="close"
  >
    <!-- 权限点数据展示 -->
    <el-tree
      ref="tree"
      :data="list"
      :props="{ label: 'name' }"
      show-checkbox
      check-strictly
      node-key="id"
    />
    <template #footer>
      <el-button @click="$emit('update:showAssignDialog')">取消</el-button>
      <el-button type="primary" @click="assignPerm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { transformTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    showAssignDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      list: [], // 存储权限数据
      roleId: '' // 当前点击的角色的id
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 关闭弹层执行
    close () {
      this.$emit('update:showAssignDialog')
      this.$refs.tree.setCheckedKeys([])
    },
    // 获取角色列表
    async getList () {
      const res = await getPermissionList()
      this.list = transformTreeData(res)
    },
    // 回显数据 id: 当前点击的角色的id
    async showAssign (id) {
      /**
       * 1.调用接口回显数据
       * 2.存储id
       */
      this.roleId = id
      const { permIds } = await getRoleDetail(id)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 存储修改后的权限分配
    // {id:角色id, permIds:[] 所有选中的节点的id组成的数组}
    async assignPerm () {
      await assignPerm({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配成功')
      this.$emit('update:showAssignDialog')
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
